import BleSDK from './BleSDK'
import agreement from './RgjAgreeB.js'
import {
  get07UpdateMaterial
} from './RgjAgreeC.js'

class RgjBleHelper {
  // 蓝牙初始化
  static BLUE_DYE_COLOR_INIT = 0
  // 开始使用蓝牙下料
  static BLUE_DYE_COLOR_START = 1
  // 蓝牙下料成功
  static BLUE_DYE_COLOR_SUCCESS = 2
  // 蓝牙下料失败
  static BLUE_DYE_COLOR_FAILED = 3
  // 蓝牙下料超时
  static BLUE_DYE_COLOR_TIMEOUT = 4
  // 蓝牙下料完成
  static BLUE_DYE_COLOR_FINISH = 5
  // 蓝牙状态错误
  static BLUE_STATUS_FAILED = 6
  // 蓝牙服务错误
  static BLUE_SERVICE_FAILED = 7

  constructor(options) {
    // 用于保存蓝牙指令
    this.hex = ''
    this.command = ''
    this.deviceId = ''
    this.serviceId = '000018FE-0000-1000-8000-00805F9B34FB'
    // 状态变更通知回调
    this.statusChangeCallback = options.statusChangeCallback
    this.status = RgjBleHelper.BLUE_DYE_COLOR_INIT
    this.statusChangeCallback(this.status)
    // 重试次数
    this.queryStatusRetryCount = 3
    // 重试间隔
    this.queryStatusDelay = 2000
    // 当前重试次数
    this.currentRetryCount = 0
    // 定时器
    this.timer = null
    // 蓝牙名称
    this.bleName = ''
    // 蓝牙数据
    this.btData = ''
    // 蓝牙指令
    this.getHex = ''
    // 蓝牙接收的值
    this.receiveValue = ''
    // 是否写入成功
    this.isWriteSuccess = false
    // 下发次数
    this.writeTimes = 0
    // 查询到的设备，防止写入数据失败后能省去重新搜索的事件
    this.device = []
    // 是否链接
    this.isConnected = false
    // 是否超时
    this.isTimeout = false
    // 当前指令
    this.currentCommand = ''
    // 蓝牙sdk实例
    this.blue = null
    // mac码
    this.mac = ''
    // 是否有获取到mac
    this.isGetMac = true
    // 色号
    this.colorNo = ''
    // 染量
    this.dyeWeight = 0
    // 模式
    this.mode = 1
    // 双氧
    this.oxydolVal = ''
    // 双氧类型
    this.oxydolType = 1
    // 配方
    this.formulaId = ''
    // 提交id
    this.commitId = ''
    // clist
    this.cList = []
  }

  async initConnectionBLE() {
    return new Promise(async (resolve, reject) => {
      if (!this.isConnected) {
        this.isConnected = await this.blue.handleInitToBLEConnection()
        resolve(this.isConnected)
      } else {
        setTimeout(() => {
          resolve(this.isConnected)
        }, 200)
      }
    })
  }

  async initBLEStatus() {
    return new Promise(async (resolve, reject) => {
      console.log('初始化蓝牙状态')
      try {
        if (this.isConnected) await this.blue.closeBLEConnection()
        await this.blue.closeBluetoothAdapter()
      } catch (error) {
        this.isConnected = false
        this.isWriteSuccess = false
        this.getHex = ''
        this.receiveValue = ''
        this.btData = ''
        this.writeTimes = 0
        this.isTimeout = false
        this.currentCommand = ''
      }
      this.isConnected = false
      this.isWriteSuccess = false
      this.getHex = ''
      this.receiveValue = ''
      this.btData = ''
      this.writeTimes = 0
      this.isTimeout = false
      this.currentCommand = ''
      resolve()
    })
  }

  async initBlue(mac) {
    this.blue = new BleSDK({
      serviceId: this.serviceId,
      mac: mac || this.mac,
      notify: async (content) => {
        console.log('notify---------------------------------------' + this.currentCommand)
        // notify回调，超时状态改成false
        this.isTimeout = false
        this.btData = this.btData + content
        console.log(this.btData)
        let responseVo = agreement.verifyBRgj(this.btData)
        console.log('responseVo-----------------------------', responseVo)
        // 协议解析完成 开始进行下一步操作
        switch (this.currentCommand) {
          case 'receiveBleResponse':
            this.receiveBleResponse(responseVo)
            break
        }
        // 接收成功以后 清空分包指令
        this.btData = ''
      },
      bleStatusCallBack: async (status) => {
        if (status == BleSDK.BLUE_STATUS_FAILED) {
          this.status = RgjBleHelper.BLUE_STATUS_FAILED
          this.statusChangeCallback(this.status)
        } else if (status == BleSDK.BLUE_SERVICE_FAILED) {
          this.status = RgjBleHelper.BLUE_SERVICE_FAILED
          this.statusChangeCallback(this.status)
        }
      }
    })
    this.isConnected = await this.initConnectionBLE()
    console.log(`连接${this.isConnected ? '完成，准备下发指令' : '失败'}`)
  }

  // 开始下料
  startDyeColor(mac, colorNo, dyeWeight, commitId, cList) {
    this.mac = mac
    this.mode = 1
    this.colorNo = colorNo
    this.dyeWeight = dyeWeight
    this.commitId = commitId
    this.cList = cList
    console.log(mac, colorNo, dyeWeight, commitId, cList)
    wx.showLoading({
      title: '下料中'
    })
    this.startBLEDyeColor()
  }

  // 连发三次指令操作
  writeValueUntilWriteSucceed(hex, command) {
    return new Promise(async (resolve, reject) => {
      console.log('isConnected: ', this.isConnected)
      if (this.isConnected) {
        clearInterval(this.timer)
        this.timer = null
        this.writeTimes = 0
        setTimeout(async () => {
          this.isWriteSuccess = await this.blue.writeValueToBLE(hex)
          this.currentCommand = command
          this.timer = setInterval(async () => {
            if (this.isWriteSuccess) {
              clearInterval(this.timer)
              this.isTimeout = true
              setTimeout(() => {
                if (this.isTimeout) {
                  this.status = RgjBleHelper.BLUE_DYE_COLOR_TIMEOUT
                  this.statusChangeCallback(this.status)
                }
              }, 6000)
              resolve(true)
              return
            }
            this.isWriteSuccess = await this.blue.writeValueToBLE(hex)
            this.writeTimes++
            console.log('this.isWriteSuccess', this.isWriteSuccess)
            console.log('this.writeTimes', this.writeTimes)
            if (this.writeTimes >= 3) {
              this.status = RgjBleHelper.BLUE_DYE_COLOR_TIMEOUT
              this.statusChangeCallback(this.status)
              resolve(false)
              wx.showModal({
                content: '连接超时，设备不在线或正在被使用',
                confirmText: '确认',
                cancelText: '取消',
                success: (res) => {
                  wx.hideLoading()
                }
              })
            }
          }, 2000)
        }, 200)
      }
    })
  }

  takeHex(hex, off, length) {
    try {
      if (hex == null || hex.length % 2 != 0) {
        return "";
      }
      if ((off * 2 + length * 2) > hex.length) {
        return "";
      }
      var beginIndex = off * 2;
      var endIndex = beginIndex + length * 2;
      return hex.substring(beginIndex, endIndex);
    } catch (e) {}
    return "";
  }

  async handleEnsureConnected() {
    return new Promise(async (resolve, reject) => {
      this.isConnected = await this.initConnectionBLE()
      if (!this.isConnected) {
        await this.initBLEStatus()
        this.status = RgjBleHelper.BLUE_DYE_COLOR_TIMEOUT
        this.statusChangeCallback(this.status)
        return
      }
      resolve()
    })
  }

  // 向设备发送16指令，下料
  async startBLEDyeColor() {
    await this.handleEnsureConnected()
    console.log(this.mac, this.mode, this.colorNo, this.dyeWeight, this.commitId, this.cList);
    this.getHex = agreement.getSetColor2(this.mac, this.mode, this.colorNo, this.dyeWeight, this.commitId, this.cList)
    console.log(this.getHex, 1231123);
    this.currentCommand = 'receiveBleResponse'
    this.isWriteSuccess = await this.blue.writeValueByTimes(this.getHex)
  }

  async receiveBleResponse(responseVo) {
    clearInterval(this.timer)
    this.timer = null
    this.btData = ''
    wx.hideLoading()
    var res = this.takeHex(responseVo.param, 2, 1)
    console.log('下料结果：' + res)
    if (res == '00') {
      this.status = RgjBleHelper.BLUE_DYE_COLOR_FINISH
      this.statusChangeCallback(this.status)
      return
    }

    if (res == '01') {
      wx.showModal({
        content: '校验出错',
        confirmText: '确认',
        cancelText: '取消'
      })
    } else if (res == '02') {
      wx.showModal({
        content: '未放料碗',
        confirmText: '确认',
        cancelText: '取消'
      })
    } else if (res == '03') {
      wx.showModal({
        content: '上次料碗未拿开',
        confirmText: '确认',
        cancelText: '取消'
      })
    } else {
      wx.showModal({
        content: '下料失败，请重试！' + res,
        confirmText: '确认',
        cancelText: '取消'
      })
    }
    this.status = RgjBleHelper.BLUE_DYE_COLOR_FAILED
    this.statusChangeCallback(this.status)
  }

  async startReloadDyeColor(mac, val) {
    this.mac = mac
    await this.handleEnsureConnected()
    console.log(this.mac, val)
    this.getHex = agreement.getReloadColor(this.mac, val)
    // this.currentCommand = 'receiveBleResponse'
    this.isWriteSuccess = await this.blue.writeValueByTimes(this.getHex)
    if (this.isWriteSuccess) {
      this.status = RgjBleHelper.BLUE_DYE_COLOR_FINISH
      this.statusChangeCallback(this.status)
    }
  }

  // 打开适配器
  openBluetoothAdapter() {
    this.blue.openBluetoothAdapter()
  }

  // 断开适配器
  closeBluetoothAdapter() {
    this.blue.closeBluetoothAdapter()
  }

  // 断连
  closeBLEConnection() {
    this.blue.closeBLEConnection()
  }
}

export default RgjBleHelper